import { createRouter, createWebHistory } from 'vue-router'
import { toRaw } from 'vue'
import { defineAsyncComponent } from 'vue'

const files = import.meta.globEager("./modules/*.js")
const modulesRouter = []
for (const path in files) {
  const moduleName = path.replace(/(.*\/)*([^.]+).*/gi, '$2')
  modulesRouter.push(files[path].default)
}
const views = {
  path: '/',
  name: 'Layout',
  component: () => import('@/layout/index.vue'),
  redirect: '/dashboard',
  children: [
    {
      name: 'dashboard',
      path: '/dashboard',
      component: () => import('@/views/dashboard/index.vue'),
      meta:{
        title: '首页',
        show: true
      }
    }
  ],
}
const routes = [
  {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        title: "登录"
      }
  },
  {
      path: '/401',
      name: '401',
      component: () => import('@/views/error/401.vue'),
      icon: '',
      meta: {
        title: '401',
      }
  },
  {
      path: '/404',
      name: '404',
      component: () => import('@/views/error/404.vue'),
      meta: {
        title: '404',
      }
  },
]
// 加载路由对应的文件
function viewFunc(path) {
  return () => import(`../views${path}.vue`)
}

function getModules() {
  const components = import.meta.glob('../views/**/*.vue')
  return components
}
export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes.concat(views, ...modulesRouter),
  strict: true
})

// 挂载路由
export function loadRouter(app) {
  app.use(router)
  return router
}
export function useRouter() {
  return router
}
// 加载路由
export async function loadRoutes({store}){
  let viewRoutes = toRaw(store.state.account.routes)
  let btnResource = toRaw(store.state.account.btnResource)
  if(!store.state.app.token){
    return false
  }
  if (!viewRoutes.length) {
    viewRoutes = await store.dispatch('account/generateRoutes')
    generateDynamicRoutes(viewRoutes)
  } else {
    generateDynamicRoutes(viewRoutes)
  }
  if(!btnResource.length){
    store.dispatch('account/generateButton')
  }
}
// 动态添加路由
export function generateDynamicRoutes(list = [], routes = []){
  let temp = []
  for (let i = 0; i < list.length; i++) {
    if (list[i].children && list[i].children.length >= 1) {
      temp = temp.concat(list[i].children)
    } else {
      let route = {
        path: list[i].url || '/dashboard',
        component: null,
        name: list[i].name,
        meta: {
          menuId: list[i].id,
          title: list[i].label,
          noCache: list[i].noCache
        }
      }
      const modules = import.meta.glob('../views/**/*.vue')
      route.component = modules[`../views${list[i].component}.vue`]
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    generateDynamicRoutes(temp, routes)
  } else {
    // console.log('路由异步加载')
    views.children = views.children.concat(routes)
    router.addRoute(views)
  }

  // 在动态路由添加后，在将404添加进入，解决刷新是找不到路由跳转404
  router.addRoute({
    path: '/:pathMatch(.*)',
    redirect: '/404'
  })

}
